﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

    /// <summary>
    /// Class which deals with serializing/deserializing data to/from binary file
    /// </summary>
    public class FileAccessor : IFileIO
    {
        #region IFileIO Members

        /// </summary>
        /// Method to save object to file
        /// </summary>
        /// <param name="fileName">Name of the file selected, or new file name</param>
        /// <param name="objectToSave">Object that needs saving</param>
        /// <returns>Returns true if saved properly</returns>
        public bool Save(string fileName, object objectToSave)
        {
            try
            {
                Stream stream = File.Open(fileName, FileMode.Create);
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(stream, objectToSave);
                stream.Close();
                return true;
            }
            catch
            {
                // If error occurs
                return false;
            }
            
        }

        /// <summary>
        /// Returns an object read from binary file
        /// </summary>
        /// <param name="fileName">File name</param>
        /// <returns>Object</returns>
        public object Load(string fileName)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            // Read object from file
            Stream stream = File.Open(fileName, FileMode.Open);
            object readObject = (object)binaryFormatter.Deserialize(stream);
            stream.Close();

            return readObject;
        }

        #endregion
    }

